﻿#region

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel.DomainServices.Client;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Navigation;
using NetBay.Core.BusinessEntities;
using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.AppCode.ApplicationNavigation;
using Telerik.Windows.Controls;
using WindowStartupLocation = Telerik.Windows.Controls.WindowStartupLocation;

#endregion

namespace Rio.Framework.Pages.ChildWindows
{
    public partial class EmailWindow
    {
        #region Readonly & Static Fields

        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof (string), typeof (EmailWindow), null);

        private readonly Organization _currentOrganization;
        private readonly List<Document> _listDocument;
        private readonly string _parameterStorage = string.Empty;

        private bool _isFolderLinkAdded;

        #endregion

        #region Fields

        private List<string> _attachFiles;
        private List<string> _attachFilesName;
        private string _emailFormatMsg = string.Empty;
        private string[] _emailToList;
        private bool _isHypperLink;
        private string _mandatoryFieldMsg = string.Empty;

        #endregion

        #region Constructors

        public EmailWindow()
        {
            InitializeComponent();
            KeyUp += MessageBoxChildWindow_KeyUp;
            InitLabel();

            CanMove = true;
            ResizeMode = ResizeMode.NoResize;
            WindowStartupLocation = WindowStartupLocation.CenterScreen;
        }

        /// <summary>
        ///   Constructor
        /// </summary>
        /// <param name="organization"> The p_o organization. </param>
        /// <param name="documentList"> Document List </param>
        /// <param name="parameterStorage"> File main storage </param>
        /// <param name="object"> Mail subject which can be null </param>
        public EmailWindow(Organization organization, List<Document> documentList, string parameterStorage, string @object = "")
            : this()
        {
            _listDocument = documentList;
            ObjectTextBox.Text = @object;
            _parameterStorage = parameterStorage;
            _currentOrganization = organization;
            if (_currentOrganization == null)
            {
                AttachedFile.IsChecked = true;
                HypperLink.IsChecked = false;
            }
            else
            {
                AttachedFile.IsChecked = true;
                HypperLink.IsChecked = false;
            }
        }

        #endregion

        #region Instance Properties

        public string Title
        {
            get
            {
                return (string) GetValue(TitleProperty);
            }
            set
            {
                SetValue(TitleProperty, value);
            }
        }

        #endregion

        #region Instance Methods

        /// <summary>
        ///   This method checks the email list format
        /// </summary>
        /// <param name="p_sEmailAddressList"> </param>
        /// <returns> </returns>
        private bool CheckEmailList(string p_sEmailAddressList)
        {
            string[] emailList = p_sEmailAddressList.TrimEnd(';').Split(';');
            bool isMatch = true;
            const string matchEmailPattern = @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"
                                             + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."
                                             + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
                                             + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})$";

            foreach (string l_sEmail in emailList)
            {
                isMatch = Regex.IsMatch(l_sEmail, matchEmailPattern);
                if (!isMatch)
                {
                    break;
                }
            }
            return isMatch;
        }

        private void InitLabel()
        {
            buttonSend.Content = Resx.GetLabel(ResxCommon.SEND);
            buttonCancel.Content = Resx.GetLabel(ResxCommon.CANCEL);
            LabelTo.Content = Resx.GetLabel(ResxCommon.TO) + " :";
            LabelObject.Content = Resx.GetLabel(ResxCommon.OBJECT) + " :";
            LabelMemo.Content = Resx.GetLabel(ResxCommon.MEMO) + " :";
            _mandatoryFieldMsg = Resx.GetLabel(ResxCommon.VALIDATE_MSG);
            _emailFormatMsg = Resx.GetLabel(ResxCommon.EMAIL_FORMAT_MSG);
            HypperLink.Content = Resx.GetLabel(ResxEmailWindow.HYPERLINK);
            AttachedFile.Content = "Pièce jointe"; 
            Title = "E-Mail"; 
        }

        /// <summary>
        ///   Validate mandatoryFields
        /// </summary>
        /// <returns> </returns>
        private bool ValidateFields()
        {
            bool l_bValidationResult = !string.IsNullOrEmpty(ToTextBox.Text);

            if (string.IsNullOrEmpty(ObjectTextBox.Text))
            {
                l_bValidationResult = false;
            }

            return l_bValidationResult;
        }

        #endregion

        #region Event Handling

        private void Instance_FolderLinkBuilded(object sender, NavigationEventArgs e)
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            MemoTextBox.Text += "Lien vers le dossier: " + e.Uri.OriginalString;
            l_oBEDomainContext.SendEMail(ObjectTextBox.Text, MemoTextBox.Text, _emailToList, _attachFiles, _attachFilesName, delegate { }
                                         , null);
        }

        private void MessageBoxChildWindow_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                DialogResult = false;
                Close();
            }
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }

        /// <summary>
        ///   Event called when the user clicks on the send button
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        private void buttonSend_Click(object sender, RoutedEventArgs e)
        {
            BusinessEntitiesDomainContext l_oBEDomainContext = new BusinessEntitiesDomainContext();
            ((WebDomainClient<BusinessEntitiesDomainContext.IBusinessEntitiesDomainServiceContract>) l_oBEDomainContext.DomainClient).ChannelFactory.Endpoint.Binding.SendTimeout = new TimeSpan(1, 0, 0);

            if (ValidateFields())
            {
                if (CheckEmailList(ToTextBox.Text))
                {
                    _emailToList = ToTextBox.Text.Split(';');
                    _attachFiles = new List<string>();
                    _attachFilesName = new List<string>();
                    HtmlPage.Document.DocumentUri.AbsoluteUri.Replace(HtmlPage.Document.DocumentUri.LocalPath, String.Empty);

                    foreach (Document l_oDoc in _listDocument)
                    {
                        if (!_isHypperLink)
                        {
                            _attachFiles.Add(Path.Combine(_parameterStorage, l_oDoc.RelativePath) + @"\" + l_oDoc.ImageName);
                            _attachFilesName.Add(l_oDoc.OriginalNameFile);
                            l_oBEDomainContext.SendEMail(ObjectTextBox.Text, MemoTextBox.Text, _emailToList, _attachFiles, _attachFilesName, delegate { }
                                                         , null);
                        }
                    }

                    DialogResult = true;
                    Close();
                }
                else
                {
                    //Email address bad format
                    ValidatorMsg.Text = _emailFormatMsg;
                    ValidatorMsg.Visibility = Visibility.Visible;
                }
            }
            else
            {
                ValidatorMsg.Text = _mandatoryFieldMsg;
                ValidatorMsg.Visibility = Visibility.Visible;
            }
        }

        private void radioButton1_Click(object sender, RoutedEventArgs e)
        {
            RadioButton l_oSelectedRadio = (RadioButton) sender;
            _isHypperLink = l_oSelectedRadio.Name.Equals("HypperLink");
            if (_currentOrganization != null && _isHypperLink)
            {
                var doc = _listDocument.First();
                NavigationHelper.Instance.FolderLinkBuilded += Instance_FolderLinkBuilded;
                NavigationHelper.Instance.GetFolderLink(_currentOrganization.Identifier, doc.FolderTypeIdentifier, doc.FolderId, doc.FolderIdentifier);
            }
        }

        #endregion
    }
}